package com.woniu.qqmaster.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniu.qqmaster.entity.QQUserBO;
import com.woniu.qqmaster.entity.Qquser;
import com.woniu.qqmaster.mapper.QqUserMapper;
import com.woniu.qqmaster.utils.MyConstantsEnum;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Optional;

/**
 * @Author dlb
 * @Date 2022/12/29 15:25
 */
@Controller
public class HomeController {
    @Autowired
    QqUserMapper qqUserMapper;

//    @ApiOperation("登录成功后进入首页，该接口会访问数据库查询好友清单，返回xxx")
//    @GetMapping("/home")
//    public ModelAndView home(ModelAndView mav) {
//
//        // 查询 54789625 qq的好友信息
////        IPage<QQUserBO> page = new Page<>(0,5);
//        List<QQUserBO> qqUserBOList = qqUserMapper.getInfoByUserId("54789625L");
//        qqUserBOList.forEach(System.out::println);
////        mav.setViewName("/list.html");
//        mav.setViewName("/list.html");
//        mav.addObject("qqUserBOList",qqUserBOList);
//        return mav;
//    }

    @ApiOperation("登录成功后进入首页，该接口数据库查询好友清单，返回IPage")
    @RequestMapping(value = "/home" , method = RequestMethod.GET)
    public ModelAndView home(HttpSession session , ModelAndView mv , @RequestParam(value = "pageIndex",defaultValue = "1")Integer pageIndex) {
        final Long loginQQId = Optional.ofNullable(session.getAttribute(MyConstantsEnum.USER.getValue())).map(e -> (((Qquser) e).getQqid())).orElse(null);
        Optional.of(loginQQId).ifPresent(e-> {
            // 构造查询条件...
            QueryWrapper<QQUserBO> wrapper = new QueryWrapper();
            wrapper.eq("r.QQID",loginQQId);
            IPage<QQUserBO> page = MyConstantsEnum.pageRangeInstance(pageIndex, 10);
            mv.addObject(MyConstantsEnum.DATA.getValue(), qqUserMapper.getInfoByUserId(page,wrapper));
            mv.setViewName("list");
        });
        return mv;
    }

    @GetMapping("/list")
    @ResponseBody
    @ApiOperation("登录成功后进入首页，返回 json 格式数据！！")
    public Object list(HttpSession session , @RequestParam(value = "pageIndex",defaultValue = "1")Integer pageIndex){
        final Long loginQQId = Optional.ofNullable(session.getAttribute(MyConstantsEnum.USER.getValue())).map(e -> (((Qquser) e).getQqid())).orElse(null);
            // 构造查询条件...
            QueryWrapper<QQUserBO> wrapper = new QueryWrapper();
            wrapper.eq("r.QQID",loginQQId);
            IPage<QQUserBO> page = MyConstantsEnum.pageRangeInstance(pageIndex, 10);
            qqUserMapper.getInfoByUserId(page,wrapper);
            return page;
    }

}
